// 配置导航守卫
import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { asyncRoutes } from '@/router'

NProgress.configure({ showSpinner: false })
const whiltList = ['/login']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    // 判断vuex中userInfo中是否有数据
    if (!store.state.user.userInfo.username) {
      try {
        await store.dispatch('user/getUserInfo')
        const { roles } = store.state.user.userInfo
        const otherRoutes = asyncRoutes.filter(item => {
          return roles.menus.includes(item.children[0].name)
        })
        store.commit('permission/setRouter', otherRoutes)
        // console.log(otherRoutes)
        // 404配置在这里是因为这里要发请求动态路由还没加载
        router.addRoutes([...otherRoutes, { path: '*', redirect: '/404', hidden: true }])
        // 解决白屏问题：在addRoutes()之后第一次访问被添加的路由会白屏，这是因为刚刚addRoutes()就立刻访问被添加的路由，然而此时addRoutes()没有执行结束，因而找不到刚刚被添加的路由导致白屏。因此需要从新访问一次路由才行。
        next({ ...to, replace: true })
      } catch {
        store.commit('user/removeToken')
        next('/login')
        NProgress.done()
      }
    }
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      next()
    }
  } else {
    // 去的路径是否在白名单中
    if (whiltList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
